import { AvatarDropdown, AvatarName, Footer, Question, SelectLang } from '@/components';
import { CloseCircleOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import { history, Link } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import React from 'react';
import { Modal } from 'antd';
import { stringify } from 'querystring';
import { clearToken, getToken } from '@/utils/Auth';
import { IconMap } from '@/components/MenuIcon';
import Icon from '@ant-design/icons/es';
import { downloadFileUrl } from '@/services/system/file';
import './global.less';
import MultiTabs from '@/components/MultiTabs';
import { API } from '@/services/typings';
import { currentUser } from '@/services/auth';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

function mapTree(item: any) {
  if (!item) {
    return item;
  }
  const haveChildren = Array.isArray(item.children) && item.children.length > 0;
// eslint-disable-next-line no-param-reassign
  item = {
    ...item,
    icon:
      typeof item.icon === 'string' && item.icon.indexOf('|svg') > -1 ? (
        <Icon
          component={IconMap[item.icon.replace('|svg', '')]}
          style={{fontSize: 24, marginRight: 8}}
        />
      ) : (
        item.icon
      ),
    children: haveChildren ? item.children.map((i: any) => mapTree(i)) : [],
  };
  return item;
}

interface InitialStateType {
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitialStateType> {
  const fetchUserInfo = async () => {
    try {
      const msg = await currentUser({
        skipErrorHandler: true,
      });
      return msg.data;
    } catch (error) {
      const token = getToken();
      if (token && !sessionStorage.getItem('authModalShown')) {
        sessionStorage.setItem('authModalShown', 'true');
        const {confirm} = Modal;
        confirm({
          title: '获取用户信息失败',
          icon: <CloseCircleOutlined style={{color: '#ff4d4f'}}/>,
          okText: '重新登录',
          content: '获取用户信息失败，请重新登录',
          okCancel: false,
          onOk() {
            clearToken()
            sessionStorage.removeItem('authModalShown');
            history.push(loginPath);
          },
        });
      }
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const {location} = history;
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: any = ({initialState, setInitialState}: any) => {
  return {
    actionsRender: () => [
      <Question key="doc"/>,
      <SelectLang key="SelectLang"/>,
    ],
    avatarProps: {
      src: downloadFileUrl(initialState?.currentUser?.avatar),
      title: <AvatarName/>,
      render: (_: any, avatarChildren: any) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.contactName,
    },
    footerRender: () => <Footer/>,
    onPageChange: async () => {
      const token = getToken();
      if (token && !initialState?.currentUser) {
        await initialState?.fetchUserInfo!();
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children: any) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <MultiTabs>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState: any) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </MultiTabs>
      );
    },
    ...initialState?.settings,
    menu: {
      params: initialState,
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      request: async (params: any, defaultMenuData: any) => {
        const curMenu = defaultMenuData.filter(
          (x: any) => x.permission === undefined || params?.currentUser?.permissions.includes(x.permission),
        );
        return curMenu.map((item: any) => {
          return mapTree(item);
        });
      },
      autoClose: false,
    },
    menuItemRender: (menuItemProps: any, defaultDom: any) => {
      if (!menuItemProps.path) {
        return defaultDom;
      }
      if (menuItemProps.isUrl) {
        return <a
          href={menuItemProps.path}
          target="_blank"
          rel="noopener noreferrer"
          style={{display: 'flex', alignItems: 'center'}}
        >
          {menuItemProps.pro_layout_parentKeys &&
            menuItemProps.pro_layout_parentKeys.length > 0 &&
            menuItemProps.icon}
          {defaultDom}
        </a>
      }

      return (
        <Link to={menuItemProps.path} style={{display: 'flex', alignItems: 'center', gap: '8px'}}>
          {menuItemProps.pro_layout_parentKeys &&
            menuItemProps.pro_layout_parentKeys.length > 0 &&
            menuItemProps.icon}
          {defaultDom}
        </Link>
      );
    },
  };
};


export const onRouteChange = () => {
  const {location} = history;
  // 如果没有登录，重定向到 login
  const token = getToken();
  if (!token && location.pathname !== loginPath) {
    history.push({
      pathname: loginPath,
      search: stringify({
        redirect: location.pathname,
      }),
    });
  } else if (token && location.pathname === loginPath) {
    history.push('/');
  }

}

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
